import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ConfigModule } from '../config.module';
import { PermissionDict } from '../models/system/permission-dict.model';
import { environment } from '../../environments/environment';

@Injectable({
    providedIn: 'root'
})
export class CommonService {
    base = 'web/';
    constructor(private _http: HttpClient, private _config: ConfigModule) {}

    /**
     * 获取所有权限字典
     */
    getAllPermissionDicts(): Observable<PermissionDict[]> {
        return this._http.get<PermissionDict[]>(environment.baseUrl + this.base + 'permission/getAllPermissions').pipe(
            map((res: any) => {
                if (res.code === 200) {
                    return res.data;
                }
            })
        );
    }

    /**
     * 获取微分电容曲线
     * @param formData
     */
    getDifferentialCapacitanceCurve(formData: any): Observable<any> {
        return this._http.post(environment.baseUrl + this.base + 'public/getPoint', formData, {});
    }

    /**
     * 文件下载
     * @param url 下载URL，【该URL需要加入到拦截器的白名单中】
     * @param savedName 存储在本地的文件名称加后缀
     * @param paramsObj 接口参数对象
     * @param successCallback 下载成功的回调函数
     * @param errorCallback 下载出错的回调函数
     */
     downloadFile(url: string, savedName: string, paramsObj: object, successCallback, errorCallback) {
        const params = {
            ...paramsObj
        };
        for (const key in params) {
            if (params[key] === '' || params[key] === null || params[key] === undefined) {
                delete params[key];
            }
        }
        const blobObservable = this._http.post(url, params, {
            responseType: 'blob',
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
            }),
        });
        blobObservable.subscribe((result) => {
            const contentType = 'application/octet-stream;charset=UTF-8';
            const blob = new Blob([result], { type: contentType });
            // 创建一个URL对象
            const objectURL = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = objectURL;
            a.download = savedName; // 此处的savedName为保存到本地的文件名称及后缀
            a.click();
            // 释放已创建的URL对象
            window.URL.revokeObjectURL(objectURL);
            successCallback();
        }, (error) => {
            errorCallback(error);
        });
        return blobObservable;
    }
}
